package com.mingye.model.chess;

import com.mingye.board.Board;
import com.mingye.components.BoardPanel;
import com.mingye.constants.Direction;
import com.mingye.model.grid.BaseGrid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 人
 *
 * @author daixinyi
 */
public class Person extends BaseChess {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final String PERSON_IMAGE_PATH = "person.png";

    public Person(int x, int y, Board board) {
        this.setImagePath(PERSON_IMAGE_PATH);
        this.x = x;
        this.y = y;
        this.board = board;
    }

    /**
     * 移动
     *
     * @param direction
     */
    public void move(Direction direction) {
        int x = this.getX();
        int y = this.getY();
        List<Box> boxList = board.getBoxList();
        BaseGrid nextGrid = board.findNextGrid(x, y, direction);
        if (nextGrid == null || nextGrid.isObstacleFlag()) {
            logger.info("前面第一格是障碍,无法移动");
            return;
        }
        int nextX = nextGrid.getX();
        int nextY = nextGrid.getY();
        if (boxList.contains(new Box(nextX, nextY))) {
            // 前面是箱子，判断前面第二格
            Box box = boxList.get(boxList.indexOf(new Box(nextX, nextY)));
            logger.info("前面第一格是箱子");
            nextGrid = board.findNextGrid(nextX, nextY, direction);
            if (nextGrid == null || nextGrid.isObstacleFlag()) {
                logger.info("前面第二格是障碍,无法移动");
                return;
            }

            int nextNextX = nextGrid.getX();
            int nextNextY = nextGrid.getY();
            if (boxList.contains(new Box(nextNextX, nextNextY))) {
                logger.info("前面第二格也是箱子,无法移动");
                return;
            }

            this.setLocation(nextX, nextY); // 人移动
            box.setLocation(nextNextX, nextNextY);    // 箱子移动
            afterPushBox(box);
        } else {
            // 人移动
            this.setLocation(nextX, nextY); // 人移动
        }

    }

    /**
     * 箱子移动后，相关逻辑处理
     *
     * @param box
     */
    private void afterPushBox(Box box) {
        int personX = this.getX();
        int personY = this.getY();

        BoardPanel panel = board.getBoardPanel();
        List<Food> foodList = board.getFoodList();
        // 判断人移动后所在的位置有没有食物，注意已重写了equals方法和hashCode方法
        if (foodList.contains(new Food(personX, personY))) {
            // 如果有，说明推动前，箱子是在食物上的，
            board.setFinishBoxCount(board.getFinishBoxCount() - 1);
        }
        int boxX = box.getX();
        int boxY = box.getY();
        // 判断箱子移动后所在的位置有没有食物，注意已重写了equals方法和hashCode方法
        if (foodList.contains(new Food(boxX, boxY))) {
            board.setFinishBoxCount(board.getFinishBoxCount() + 1);
            box.setImageOK();
        } else {
            box.setImageDefault();
        }
        panel.checkWin();
    }
}
